const path = require('path');//获取当前项目绝对路径
const {CleanWebpackPlugin} = require('clean-webpack-plugin');//用以清空dist文件夹
const TerserPlugin = require("terser-webpack-plugin");//防止.js.LICENSE.txt生成
const MiniCssExtractPlugin = require('mini-css-extract-plugin');//独立打包css
const HtmlWebpackPlugin = require('html-webpack-plugin');//打包html
const webpack = require('webpack');

var getHtmlConfig = function(name){
    return{
        template: './src/view/' + name + '.html',
        filename: 'view/' + name + '.html',
        inject  : true,
        hash    : true,
        chunks  : ['common',name],
        minify  : {
            collapseWhitespace: false
        }
    }
};

var config = {
    entry: {
        'common': ['./src/page/common/index.js'],
        'index' : ['./src/page/index/index.js'],
        'login' : ['./src/page/login/index.js']
    },

    output: {
        filename: 'js/[name].js',
        path    : path.resolve(__dirname, 'dist')
    },

    devServer: {
        port    : 8888,
        contentBase : path.resolve(__dirname, 'dist')
    },

    module: {
        rules: [
            {
                test: /\.css$/,
                use :[
                    {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            publicPath: '../'
                        }
                    },
                    'css-loader'
                ]
            },//CSS
            {
                test: /\.(png|svg|jpg|gif)$/,
                use :[
                    'url-loader?limit=1000&name=images/[name].[ext]'
                ]
            }//IMAGE
        ]
    },//模块

    plugins: [
        // new CleanWebpackPlugin(),
        new MiniCssExtractPlugin({
            filename: 'css/[name].css'
        }),
        new HtmlWebpackPlugin(getHtmlConfig('index')),
        new HtmlWebpackPlugin(getHtmlConfig('login')),

        new webpack.HotModuleReplacementPlugin()    //热更新
    ],//插件

    optimization: {
        minimize: false,//是否压缩代码
        minimizer: [
            new TerserPlugin({
                extractComments: false,//不将注释提取到单独的文件中
            })
        ],
        splitChunks: {
            cacheGroups: {
                commons: {
                    name        : 'util',
                    chunks      : 'all',
                    minChunks   : 2,
                    minSize     : 0
                }
            }
        }

    },//优化

    externals: {
        'jquery' : 'window.jQuery'
    },//外部扩展

    performance: {
        hints               : "warning",
        maxAssetSize        : 300000,
        maxEntrypointSize   : 500000
    }
};

module.exports = config;